package com.masq.aboard.service.impl;

import com.masq.aboard.common.util.DateUtil;
import com.masq.aboard.common.util.UUIDUtil;
import com.masq.aboard.config.LocalFileConfig;
import com.masq.aboard.service.FileManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * 本地文件上传下载
 * @author masq
 * @since 2024-05-03
 */
@Service("localFileManagerService")
public class LocalFileManagerServiceImpl implements FileManagerService {

    private final LocalFileConfig localFileConfig;

    @Autowired
    public LocalFileManagerServiceImpl(LocalFileConfig localFileConfig) {
        this.localFileConfig = localFileConfig;
    }

    @Override
    public String uploadFile(InputStream is, String ext) {
        String fileName = UUIDUtil.getUUID() + "." + ext;

        // 根据当前时间生成目录
        String path = DateUtil.dateToFilePath();
        String directory = localFileConfig.getDirectory() + "/" + path;
        File dir = new File(directory);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        String filePath = directory + "/" + fileName;
        try (OutputStream os = Files.newOutputStream(Paths.get(filePath))) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
            return filePath;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void downloadFile(OutputStream outputStream, String filePath) {
        try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
